package com.jecy.base.baseproject.controller;

import com.jecy.base.baseproject.base.service.TokenService;
import com.jecy.base.baseproject.base.utils.Md5Util;
import com.jecy.base.baseproject.domain.User;
import com.jecy.base.baseproject.domain.dto.TokenResult;
import com.jecy.base.baseproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * <p> </p>
 *
 * @author huijun
 * @create 2018-05-06 下午4:12
 **/
@RestController
@CrossOrigin
@RequestMapping("user/")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @RequestMapping(value = "token", method = RequestMethod.GET)
    public Object login(@RequestParam("username") String username, @RequestParam("password")String password) {
        try {
            String md5Password = Md5Util.EncoderByMd5(password);
            User userParam = new User();
            userParam.setUsername(username);
            User userEntity = userService.selectOne(userParam);
            if (userEntity != null) {
                if (md5Password.equals(userEntity.getPassword())) {
                    String token = tokenService.generateToken(userEntity);
                    TokenResult tokenResult = new TokenResult();
                    tokenResult.setToken(token);
                    tokenResult.setUserId(userEntity.getId());
                    return tokenResult;
                }
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping("/test")
    public Object testSelect() {
        return userService.testSelect();
    }

}
